import ResMgr from "../../../../Framework/Res/ResMgr";

export default class StateCtrl {
    //此类用于动画切换
    //状态对象
    private _target: any = null;
    private _aniComp: cc.Animation = null;
    constructor(target: any) {
        this._target = target;
        this._aniComp = this._target.node.getComponent(cc.Animation);
    }

    //存储当前的动画
    private _state: string = "Idle";

    //保存上一个动画状态
    private _preState: string = "";

    changeState(state: string) {
        //判断动画是否需要修改，因为如果按键一直按着不松开，就会不断调用此函数，所以需要使用一个状态机，防止状态被切换
        if (this._state == state) {
            return;
        }
        this._preState = this._state;
        this._state = state;
        if (this._state == "Die") {
            this._aniComp.stop();
            this._aniComp.play("RoleDie" + (this._target.roleIndex + 1));
            this._target.isDeath = true;
            return;
        }
        if (this._state == "Idle") {
            this._aniComp.stop();
            let sprite = this._target.node.getComponent(cc.Sprite);
            let atlasRes: cc.SpriteAtlas = ResMgr.instance.getRes("AtlasRes", "player");
            this._preState = this._preState == "runLeft" ? "runRight" : this._preState;
            let newSpriteFrame = atlasRes.getSpriteFrame(this._preState + (this._target.roleIndex + 1) + "_0");
            sprite.spriteFrame = newSpriteFrame;
            return;
        }
        let aniName = this.getAnimationName(this._state);
        this._aniComp.stop();
        this._aniComp.play(aniName);
    }
    getAnimationName(stateIn: string) {
        this._target.node.scaleX = (stateIn == "runLeft") ? -1 : 1;
        let state = (stateIn == "runLeft") ? "runRight" : stateIn;
        let aniName: string = state[0].toUpperCase() + state.slice(1) + (this._target.roleIndex + 1);
        return aniName;
    }
}
